//
// Created by wayne on 18-12-5.
//

#ifndef ENGINE_RACE_KEYVALUELOGMANAGER_H
#define ENGINE_RACE_KEYVALUELOGMANAGER_H

#include <string>
#include <include/polar_string.h>
#include <include/engine.h>
#include <fcntl.h>
#include "KeyLogCache.h"
#include "KeyValueLog.h"

namespace polar_race {

    class KeyValueLogManager {
    public:
        KeyValueLogManager(const std::string &path, const int &id):id(id) {

            std::ostringstream ss2;
            ss2 << path << "/value-" << this->id;
            this->valueFilePath = ss2.str();

            keyValueLogs.reserve(KeyLogPerManagerNum);

            auto mode = O_DIRECT | O_RDWR | O_NOATIME;
            this->valueFd = openOrCreateFile(valueFilePath,1024L * 1024 * 1024 * 256 / KeyManagerNum, mode);

            for (int i = 0; i < KeyLogPerManagerNum; i++) {
                keyValueLogs.emplace_back(new KeyValueLog(path, id * KeyLogPerManagerNum + i, i, this->valueFd));
            }

        }

        ~KeyValueLogManager() {
            for (auto &kvLog:keyValueLogs)
                delete kvLog;
            keyValueLogs.clear();
            close(this->valueFd);
        }

        void initialize(void *buffer) {

            for (int i = 0; i < KeyLogPerManagerNum; i++) {
                keyValueLogs[i]->initialize(buffer);
            }
        }

        std::vector<KeyValueLog *> keyValueLogs;

    private:
        int id;
        int valueFd;
        std::string valueFilePath;
    };
}


#endif //ENGINE_RACE_KEYVALUELOGMANAGER_H
